package com.lixinxinlove.jaychoumusic


import android.os.CountDownTimer
import android.os.SystemClock
import android.util.SparseArray
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.widget.AppCompatTextView
import androidx.recyclerview.widget.RecyclerView


/**
 *   author ： lixinxin
 *   time    ： 2021-12-30
 *   email：895330766@qq.com
 */
class TimeAdapter : RecyclerView.Adapter<TimeAdapter.TimeViewHolder>() {

    private val countDownMap = SparseArray<CountDownTimer>()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TimeViewHolder {

        val itemView =
            LayoutInflater.from(parent.context).inflate(R.layout.item_time_view, parent, false)
        return TimeViewHolder(itemView = itemView)

    }

    private val stopTime = 1672393318000L

    override fun onBindViewHolder(holder: TimeViewHolder, position: Int) {

        var betweenDate = stopTime - System.currentTimeMillis()

        if (position == 0) {
            betweenDate = stopTime - System.currentTimeMillis() - 100000L
        }


        holder.countDownTimer?.cancel()


        holder.countDownTimer = object : CountDownTimer(betweenDate, 1000) {

            override fun onTick(millisUntilFinished: Long) {
                holder.clock.text = "${millisUntilFinished / 1000}"
            }

            override fun onFinish() {
                holder.clock.text = "结束"
            }
        }.start()


        //长度固定
        countDownMap.put(holder.clock.hashCode(), holder.countDownTimer)
    }

    override fun getItemCount(): Int {
        return 30
    }


    inner class TimeViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val clock: AppCompatTextView = itemView.findViewById(R.id.time_text)
        var countDownTimer: CountDownTimer? = null
    }


    /**
     * 清空资源
     */
    public fun cancelAllTimers() {
        if (countDownMap == null) {
            return
        }

        for (i in 0 until countDownMap.size()) {
            val cdt = countDownMap.get(countDownMap.keyAt(i))
            if (cdt != null) {
                cdt.cancel()
            }
        }
    }

}